package com.eco.fanliapp.job.sytimeperiodgoodsjob;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.CollectionHandleUtils;
import com.eco.fanliapp.utils.DateFormatUtils;
import org.apache.commons.collections.CollectionUtils;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 根据商品标签，获取秒杀商品
 */
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class Task1 implements Job, Serializable {


    private static final Logger log = LoggerFactory.getLogger(Task1.class);

    @Autowired
    private ISyTimePeriodGoodsService syTimePeriodGoodsService;
    @Autowired
    private ISyTimePeriodService syTimePeriodService;


    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        //取得job详情
        JobDetail jobDetail = context.getJobDetail();

        JobDataMap dataMap =  jobDetail.getJobDataMap();

        int executeCount = 0;
        if (dataMap.containsKey("runCount")) {
            executeCount = dataMap.getInt("runCount");
        }

        // 增量计数并将其存储回 JobDataMap，这样可以适当保持工作状态
        executeCount++;
        dataMap.put("runCount", executeCount);

        long startTime1 = System.currentTimeMillis();
        log.info("***************************************开始执行根据商品标签，获取秒杀商品任务-Task1：executeCount="+executeCount+"--startTime="+startTime1);

        //根据创建日期搜索商品
        String startTime = DateFormatUtils.getNowDateDay(new Date()) + " " + "00:00:00";
        String endTime = DateFormatUtils.dateToString(new Date());


        //根据标签拉去当天的商品（开始和结束日期废弃）
        List<AppGoods> appGoods = syTimePeriodGoodsService.getTimePeriodGoods(startTime,endTime);

        //分配到不同时段秒杀的商品
        if(CollectionUtils.isNotEmpty(appGoods)){
            log.info("开始获取时间段列表");
            //获取时间段列表
            QueryWrapper<SyTimePeriod> query = new QueryWrapper<>();
            query.eq("enable",1);
            query.eq("deleted",0);
            List<SyTimePeriod> periods = syTimePeriodService.list(query);
            int pageSize = 0;
            if(CollectionUtils.isNotEmpty(periods)){
                pageSize = periods.size();
            }else{
                log.info("未设置秒杀时间段");
                return;
            }

            //切分集合
            List<List<AppGoods>> lists = CollectionHandleUtils.splitList(appGoods, pageSize);
            for(int i=0; i<lists.size(); i++){
                //将商品和时间批次对应
                SyTimePeriod syTimePeriod = periods.get(i);
                addSyTimePeriodGoods(lists.get(i),syTimePeriod);
            }
        }
        long endTime1 = System.currentTimeMillis();
        log.info("***************************************结束执行根据商品标签，获取秒杀商品任务-Task1：executeCount="+executeCount+"--endTime="+endTime+"--耗时="+(endTime1-startTime1));
    }

    /**
     * 保存秒杀商品
     * @param appGoodsList
     * @param syTimePeriod
     */
    private void addSyTimePeriodGoods(List<AppGoods> appGoodsList,SyTimePeriod syTimePeriod){
        log.info("开始将商品同步到秒杀商品");
        List<SyTimePeriodGoods> goods = new ArrayList<>();
        for(AppGoods appGood :appGoodsList){
            SyTimePeriodGoods stpg = new SyTimePeriodGoods();
            stpg.setPeriodId(syTimePeriod.getTableId());
            stpg.setPeriodTime(syTimePeriod.getPeriodTime());
            //商品id
            log.info("商品id为{}",appGood.getItemid());
            if(appGood.getItemid()!=null && !"".equals(appGood.getItemid())){
                stpg.setItemId(Long.valueOf(appGood.getItemid()));
            }
            stpg.setItemTitle(appGood.getItemtitle());
            stpg.setItemPic(appGood.getItempic());
            stpg.setItemNum(appGood.getCouponsurplus());//取优惠券剩余数量
            stpg.setItemDesc(appGood.getItemdesc());
            stpg.setPeriodGoodsTime(new Date());
            //原价
            log.info("商品原价{}",appGood.getItemprice());
            if(appGood.getItemprice()!=null && !"".equals(appGood.getItemprice())){
                stpg.setOriginalPrice(BigDecimal.valueOf(Double.parseDouble(appGood.getItemprice())));
            }
            //折扣价
            log.info("商品折扣价{}",appGood.getItemendprice());
            if(appGood.getItemendprice()!=null && !"".equals(appGood.getItemendprice())){
                stpg.setDiscountPrice(BigDecimal.valueOf(appGood.getItemendprice()));
            }
            //放入集合，批量保存
            goods.add(stpg);
        }

        syTimePeriodGoodsService.saveBatch(goods);
        log.info("批量保存秒杀数据成功");
    }
}
